from os import mkdir, listdir
from os.path import isfile, join, lexists, split

class Directory(object):
    """Folder class
    
    Attributes:
        path: A string of directory
        files: A collection of all files in directory.
    """
    
    _path = None
    
    def __init__(self, path):
        """Initialize folder class.
        
        Args:
            path: A path to directory.
        """
        self._path = path
        self._files = []
    
    def __repr__(self):
        return self._path
    
    def __str__(self):
        return self._path
        
    @property
    def path(self):
        return self._path
    
    @staticmethod
    def create(path):
        """Static method to create folder recursively.
        
        Args:
            path: A string of path to create.
        """
        
        paths = []
        while path and not lexists(path):
            paths.insert(0, path)
            head, tail = split(path)
            if len(tail.strip()) == 0: # Just incase path ends with a / or \
                path = head
                head, tail = split(path)
            path = head
        
        for path in paths:
            mkdir(path)
    
    @property
    def files(self):
        """A list of File instance"""
        
        if self._files: return self._files
        
        from _file import File
        
        paths = [f for f in listdir(self.path) if isfile(join(self.path, f))]
        for path in paths:
            self._files.append(File(join(self.path, path)))
        
        return self._files
    